import dayjs from "dayjs";
import { Thread } from "threads";
import { InjectionToken, container } from "tsyringe";
import { Task } from "../autox/task";
import { CURRENT_TASK } from "./task";
import { Context } from "./ctx";
import { updateFloat } from "../utils";

export abstract class App {
    packageName: string;
    title: string;
    task: Task;
    constructor(packageName: string, title: string) {
        this.packageName = packageName;
        this.title = title;
        this.task = container.resolve(Task)
    }
    startTime: string = `08:00:00`;
    endTime: string = `23:00:00`;
    eachTime: number = 60 * 1000 * 30;
    close() {
        log(`离开【${this.title}】应用`)
        if (this.thread && this.thread.isAlive()) {
            this.thread.interrupt()
        }
    }
    open() {
        log(`进入【${this.title}】应用`)
        updateFloat({ currentApp: this.title })
        this.render()
        this.start();
    }

    watchRun() {
        while (true) {
            const dateStr = dayjs().format('YYYY-MM-DD')
            const now = dayjs().toDate()
            const startDate = dayjs(`${dateStr} ${this.startTime}`).toDate()
            const endDate = dayjs(`${dateStr} ${this.endTime}`).toDate()
            if (now > startDate && now < endDate) {
                return true;
            }
            return false;
        }
    }
    abstract render(): void;
    private thread: Thread;
    start(): void {
        if (this.thread && this.thread.isAlive()) {
            this.thread.interrupt()
        }
        this.thread = this.task.start(() => {
            const ctx = container.resolve(Context)
            const currentTask = ctx.get(CURRENT_TASK)
            updateFloat({currentTask: currentTask?.title})
            let canRun = currentTask && currentTask.canRun()
            log(`${canRun ? '满足运行条件' : '不满足运行条件'}`)
            while (!canRun) {
                log(`没有可执行任务，正在休息`)
                sleep(1000 * 60)
                canRun = currentTask && currentTask.canRun()
            }
            log(`正在启动${currentTask.title}`)
            currentTask.run()
        })
        this.thread.waitFor()
        log(`任务启动成功`)
    }
}
export const APPS: InjectionToken<App> = `APP`
export const CURRENT_APP: InjectionToken<App> = `CURRENT_APP`